<script setup>
import {onMounted, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import SearchInput from './SearchInput.vue';

const router = useRouter();
const route = useRoute();
let activeMenu = ref('');
//监听路由变化，实时更新activeMenu
watch(
    () => route.query.category,
    (newValue) => {
      activeMenu.value = newValue;
    }
);

const handleSelect = (index) => {
  router.push({path: '/', query: {category: index}});
};

onMounted(() => {
  const {category} = router.currentRoute.value.query || {};
  if (category) {
    activeMenu.value = category;
  }
});
</script>

<template>
  <div class="top-bar">
    <div class="top-bar-left">
      <!--   logo   -->
      <div class="logo">
        <router-link to="/" class="no-decorate"><h1>TechBlog</h1></router-link>
      </div>

      <!--   导航组件   -->
      <div class="nav">
        <el-menu :default-active="activeMenu" class="menu" mode="horizontal" :ellipsis="false" @select="handleSelect">
          <el-menu-item index="frontend">前端</el-menu-item>
          <el-menu-item index="java">Java</el-menu-item>
          <el-menu-item index="python">Python</el-menu-item>
          <el-menu-item index="miniprogram">小程序</el-menu-item>
        </el-menu>
      </div>

      <!--   搜索组件   -->
      <div class="search">
        <SearchInput />
      </div>
    </div>
    <div class="top-bar-right">
      <router-link to="/login">登录</router-link>
    </div>
  </div>
</template>

<style scoped>
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  background-color: #2e2f3f;
  color: white;
  padding: 10px; /* 可以根据需要调整内边距 */
  height: 60px;
}

.top-bar-left {
  display: flex;
  align-items: center;
}

.logo h1 {
  margin: 0; /* 移除默认的margin */
  color: inherit; /* 继承父元素的颜色 */
  text-decoration: none; /* 去掉链接下划线 */
}

.nav {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.menu {
  background-color: inherit;
  border-bottom: none; /* 去除默认下划线 */
  --el-menu-text-color: white;
  --el-menu-active-color: white;
}

.menu .el-menu-item {
  width: 150px; /* 菜单项宽度*/
  text-align: center;
  font-size: 16px; /* 增加字体大小 */
  transition: background-color 0.3s, color 0.3s; /* 平滑过渡效果 */
}

.menu .el-menu-item:hover {
  background-color: white; /* 鼠标悬停时背景颜色为白色 */
  color: black; /* 鼠标悬停时字体颜色为黑色 */
}

.menu .el-menu-item.is-active {
  background-color: inherit; /* 选中时背景颜色为黑色 */
  color: white; /* 选中时字体颜色为白色 */
}

.no-decorate {
  color: inherit;
  text-decoration: none;
}

.no-decorate:hover {
  text-decoration: underline; /* 鼠标悬停时显示下划线 */
}

.top-bar-right a {
  color: inherit;
  text-decoration: none;
}

.top-bar-right a:hover {
  text-decoration: underline; /* 鼠标悬停时显示下划线 */
}

.search {
  margin-left: 100px; /* 设置左边距 */
}
</style>